﻿Imports Telerik.Web.UI
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO

Partial Class VoucherAUTODtl
    Inherits System.Web.UI.Page
    Dim _CommandName As String
    Dim _Command As String
    Dim VoucherAUTOHdrObj As New DBVoucherAUTOHdrSP
    Dim VoucherAUTOHdrDS As New DataSet
    Dim VoucherAUTODtlObj As New DBVoucherAUTODtlSP
    Dim AccountObj As New AccountsSP
    Public strConnection As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString.ToString

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Me.Theme = GetGlobalResourceObject("SystemResource", "Theme")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim _lblPageTitle As Label
            _lblPageTitle = Me.Master.FindControl("lblPageTitle")
            _lblPageTitle.Text = GetLocalResourceObject("PageTitle")
            rdpDate.DbSelectedDate = DateTime.Now()
            rtbYear.Text = Year(Now()).ToString()

            hdnVoucherID.Value = Request.QueryString("VoucherID").ToString

            If hdnVoucherID.Value <> "" Then
                FillVoucherDtl()
            Else
                hdnVoucherID.Value = "-1"
                rdpDate.DbSelectedDate = Now    'Default Document Date is Today
                rtbYear.Text = Year(Now()).ToString()         'Default Year is the Current Year
            End If
            btnCancel.Attributes.Add("onClick", "javascript:history.back(); return false;")

        End If
    End Sub



#Region "Attachments"
    Private Sub UploadAttachments()

        Dim FileUpload As RadAsyncUpload = AsyncUploadVoucher
        lblUploadError.Visible = False
        If Not (FileUpload.UploadedFiles.Count > 0) Then
            Return
        End If

        For i As Integer = 0 To FileUpload.UploadedFiles.Count - 1


            Dim fs As System.IO.Stream = FileUpload.UploadedFiles(i).InputStream

            Dim imageBytes As [Byte]() = New [Byte](fs.Length - 1) {}
            fs.Read(imageBytes, 0, CInt(fs.Length))
            fs.Close()

            Dim strQuery As [String]

            'insert the file into database
            strQuery = "insert into tblFiles([Voucher_IDC], [Voucher_IDN],[Name], [ContentType], [Data]) values (@Voucher_IDC, @Voucher_IDN,@Name, @ContentType, @Data)"
            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@Voucher_IDC", "AV")
            cmd.Parameters.AddWithValue("@Voucher_IDN", hdnVoucherID.Value.ToString())
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = FileUpload.UploadedFiles(i).GetName()

            'Make sure we are dealing with a Compatible File Format Like JPG or GIF file
            Dim extension As String = System.IO.Path.GetExtension(FileUpload.UploadedFiles(i).GetName()).ToLower()
            Dim MIMEType As String = Nothing
            Select Case extension
                Case ".gif"
                    MIMEType = "image/gif"
                    Exit Select
                Case ".jpg", ".jpeg", ".jpe"
                    MIMEType = "image/jpeg"
                    Exit Select
                Case ".png"
                    MIMEType = "image/png"
                    Exit Select
                Case ".bmp"
                    MIMEType = "image/bmp"
                    Exit Select
                Case ".txt"
                    MIMEType = "application/txt"
                    Exit Select
                Case ".pdf"
                    MIMEType = "application/pdf"
                    Exit Select
                Case ".doc"
                    MIMEType = "application/msword"
                    Exit Select
                Case ".xls"
                    MIMEType = "application/msexcel"
                    Exit Select
                Case ".docx"
                    MIMEType = "application/vnd.ms-word"
                    Exit Select
                Case ".xlsx"
                    MIMEType = "application/vnd.ms-excel"
                    Exit Select
                Case Else
                    '   Invalid file type uploaded

                    lblUploadError.Visible = True
                    Return
            End Select

            cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = MIMEType
            cmd.Parameters.Add("@Data", SqlDbType.VarBinary).Value = imageBytes
            ' bytes;
            InsertUpdateData(cmd)

        Next

    End Sub

    Private Function InsertUpdateData(ByVal cmd As SqlCommand) As [Boolean]
        Dim con As New SqlConnection(strConnection)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            Return True
        Catch ex As Exception
            Response.Write(ex.Message)
            Return False
        Finally
            con.Close()
            con.Dispose()
        End Try
    End Function


#End Region


    Sub SaveControls()
        hdnVoucherID.Value = VoucherAUTOHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteScalar, "SaveVoucherAUTOHdr", _
                                                      hdnVoucherID.Value, rtbYear.Text, rtbVoucherNo.Text, rdpDate.DbSelectedDate, rcbType.SelectedValue, _
                                                      rcbMainCostCenter.SelectedValue, rcbCostCenter.SelectedValue, , rtbRemarks.Text)
        SaveDtl()
        UploadAttachments()
    End Sub

    Protected Sub SaveDtl()
        Dim regDate As Date = Date.Now()
        Dim strDate As String = regDate.ToString("ddMMMyyyy")

        For counter = 0 To rgVoucherAUTODtl.Items.Count - 1
            VoucherAUTODtlObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "SaveVoucherAUTODtl", rgVoucherAUTODtl.Items(counter)("ID").Text, _
            hdnVoucherID.Value, _
            IIf(rgVoucherAUTODtl.Items(counter)("TransYear").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("TransYear").Text), _
            IIf(rgVoucherAUTODtl.Items(counter)("PayOrderNo").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("PayOrderNo").Text), _
             IIf(rgVoucherAUTODtl.Items(counter)("ProgramNo").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("ProgramNo").Text), _
             IIf(rgVoucherAUTODtl.Items(counter)("AccountNo").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("AccountNo").Text), _
             IIf(rgVoucherAUTODtl.Items(counter)("CostCenterNo").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("CostCenterNo").Text), _
             IIf(rgVoucherAUTODtl.Items(counter)("Debit").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("Debit").Text), _
             IIf(rgVoucherAUTODtl.Items(counter)("Credit").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("Credit").Text), _
            CType(rgVoucherAUTODtl.Items(counter)("RecordStatus").Controls(0), HyperLink).Text, _
            Session("UserName").ToString(), Now, _
             IIf(rgVoucherAUTODtl.Items(counter)("Remarks").Text = "&nbsp;", "", rgVoucherAUTODtl.Items(counter)("Remarks").Text))
        Next
    End Sub



    Protected Sub FillVoucherDtl()
        VoucherAUTOHdrDS = VoucherAUTOHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvVoucherAUTOHdrByID", hdnVoucherID.Value)
        If VoucherAUTOHdrDS IsNot Nothing Then
            If VoucherAUTOHdrDS.Tables(0).Rows.Count > 0 Then

                rtbYear.Text = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("Year").ToString()
                rtbVoucherNo.Text = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("VoucherNo").ToString()
                rdpDate.DbSelectedDate = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("VoucherDate").ToString()
                rcbType.DataBind()
                rcbType.SelectedValue = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("VoucherType").ToString()
                rcbMainCostCenter.DataBind()
                rcbMainCostCenter.SelectedValue = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("MainCostCenter").ToString()
                rcbCostCenter.DataBind()
                rcbCostCenter.SelectedValue = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("CostCenter").ToString()
                hdnRecordStatus.Value = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("RecordStatus").ToString()
                rtbRemarks.Text = VoucherAUTOHdrDS.Tables(0).Rows(0).Item("Remarks").ToString()

                If hdnRecordStatus.Value = "2" Then 'Voucher is exported so fields disabled
                    rtbYear.Enabled = False
                End If
            End If
        End If
    End Sub


    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If rcbType.SelectedIndex = 0 Then
                Label2.Visible = True
                Exit Sub
            Else
                SaveControls()
                CleanTemp() ' This Function is to Clean The Temporary Files Stored by RadAsyncUpload in App_Data\RadUploadTemp
                RadAjaxManager1.ResponseScripts.Add("radalert('Information Saved Successfully !', 270, 100);")
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect("~/VoucherAUTOHdr.aspx")
    End Sub

    Sub CleanTemp()
        Dim dir As New DirectoryInfo(Server.MapPath("~\App_Data\RadUploadTemp"))
        Dim file As IO.FileInfo() = dir.GetFiles()
        For i = 0 To file.Length - 1
            file(i).Delete()
        Next
    End Sub
    Protected Sub rgVoucherAUTODtl_ItemCommand(ByVal source As Object, ByVal e As GridCommandEventArgs) Handles rgVoucherAUTODtl.ItemCommand
        _CommandName = e.CommandName
    End Sub

    Protected Sub rgVoucherAUTODtl_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles rgVoucherAUTODtl.ItemDataBound
        If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) And _CommandName <> "InitInsert" Then
            'If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) Then

            Dim editFormItem As GridEditFormItem = CType(e.Item, GridEditFormItem)
            Dim parentItem As GridDataItem = editFormItem.ParentItem

            Dim box As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbv"), RadComboBox)
            box.SelectedValue = parentItem("AccountNo").Text
            Dim box1 As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbd"), RadComboBox)
            box1.SelectedValue = parentItem("AccountNo").Text

            Dim box2 As RadComboBox = CType(editFormItem.FindControl("WUCCostCenter").FindControl("rcbd"), RadComboBox)
            box2.SelectedValue = parentItem("CostCenterNo").Text
        End If

    End Sub

    Protected Sub rbtnDelete_Click(sender As Object, e As System.EventArgs) Handles rbtnDelete.Click
        DeleteRecord()
    End Sub
    Sub DeleteRecord()

        Try
            VoucherAUTODtlObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "DeleteVoucherAUTODtlByVoucherID", , hdnVoucherID.Value)
            VoucherAUTOHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "DeleteVoucherAUTOHdr", hdnVoucherID.Value)
            Response.Redirect("~/VoucherHdr.aspx")

        Catch ex As Exception
            Response.Write(ex.Message)
        Finally

        End Try
    End Sub
End Class

